package datasource.review;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.util.StringTokenizer;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.alchemyapi.api.AlchemyAPI;
import com.alchemyapi.api.AlchemyAPI_Params;
import com.aliasi.util.Pair;

class SentimentTest {
	public static Pair<Integer, Double> getSentScore(String text) {
		try {
			String result = getSentiment(text);
			return parseXMLResult(result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private static String getSentiment(String text) throws IOException,
			SAXException, ParserConfigurationException,
			XPathExpressionException {
		// Create an AlchemyAPI object.
		AlchemyAPI alchemyObj = AlchemyAPI
				.GetInstanceFromFile("res/api_key.txt");
		AlchemyAPI_Params para = new AlchemyAPI_Params();
		para.setCustomParameters("showSourceText=1");
		// Extract sentiment for a text string.
		Document doc = alchemyObj.TextGetTextSentiment(text, para);
		return getStringFromDocument(doc);
	}

	private static Pair<Integer, Double> parseXMLResult(String result) {
		StringTokenizer st = new StringTokenizer(result, "\n");
		Integer sentiment = null;
		Double score = null;
		while (st.hasMoreTokens()) {
			String line = st.nextToken();
			if (line.contains("<status>") && line.contains("</status>")) {
				if (!line.contains("OK")) {
					return null; // http request failure
				}
			}

			if (line.contains("<type>") && line.contains("</type>")) {
				sentiment = 0;
				if (line.contains("positive")) {
					sentiment = 1;
				}
				if (line.contains("negative")) {
					sentiment = -1;
				}

			}
			if (line.contains("<score>") && line.contains("</score>")) {
				int s = line.indexOf('>');
				int e = line.lastIndexOf('<');
				score = Double.parseDouble(line.substring(s + 1, e));
			}
		}
		if (sentiment != null && score != null) {
			return new Pair<Integer, Double>(sentiment, score);
		}
		return null;
	}

	public static void main(String[] args) throws IOException, SAXException,
			ParserConfigurationException, XPathExpressionException {
		String xmlResult = getSentiment("I really really love this idea. It's perfect.");
		Pair<Integer, Double> sentResult = parseXMLResult(xmlResult);
		System.out.println(sentResult.a() + " " + sentResult.b());
	}

	// utility function
	private static String getFileContents(String filename) throws IOException,
			FileNotFoundException {
		File file = new File(filename);
		StringBuilder contents = new StringBuilder();

		BufferedReader input = new BufferedReader(new FileReader(file));

		try {
			String line = null;

			while ((line = input.readLine()) != null) {
				contents.append(line);
				contents.append(System.getProperty("line.separator"));
			}
		} finally {
			input.close();
		}

		return contents.toString();
	}

	// utility method
	private static String getStringFromDocument(Document doc) {
		try {
			DOMSource domSource = new DOMSource(doc);
			StringWriter writer = new StringWriter();
			StreamResult result = new StreamResult(writer);

			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer transformer = tf.newTransformer();
			transformer.transform(domSource, result);

			return writer.toString();
		} catch (TransformerException ex) {
			ex.printStackTrace();
			return null;
		}
	}
}
